package com.bangdream.michelia.view.activity.live;

import android.content.res.Configuration;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bangdream.michelia.R;
import com.bangdream.michelia.application.AppCurrentUser;
import com.bangdream.michelia.contract.LiveContract;
import com.bangdream.michelia.entity.LiveBean;
import com.bangdream.michelia.entity.LiveUrlBean;
import com.bangdream.michelia.entity.UserBean;
import com.bangdream.michelia.presenter.LivePersenter;
import com.bangdream.michelia.tool.LandLayoutVideo;
import com.bangdream.michelia.tool.retrofithttp.RetroFactory;
import com.bangdream.michelia.utils.DateUtil;
import com.bangdream.michelia.utils.L;
import com.bangdream.michelia.utils.ToastUtil;
import com.bangdream.michelia.view.activity.base.SwipeBackActivity;
import com.bangdream.michelia.view.activity.currency.MainActivity;
import com.bumptech.glide.Glide;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.listener.GSYVideoProgressListener;
import com.shuyu.gsyvideoplayer.listener.LockClickListener;
import com.shuyu.gsyvideoplayer.model.VideoOptionModel;
import com.shuyu.gsyvideoplayer.utils.Debuger;
import com.shuyu.gsyvideoplayer.utils.GSYVideoType;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer;
import com.zzhoujay.richtext.ImageHolder;
import com.zzhoujay.richtext.RichText;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

/**
 * 直播详情页
 */
public class LiveDetails extends SwipeBackActivity<LiveContract.ILiveView,LivePersenter<LiveContract.ILiveView>>
        implements ViewPager.OnPageChangeListener,LiveContract.ILiveView{
    private RelativeLayout titleBar;
    private ImageView head_img_right,head_img_right2,ivBg;
    private ViewPager viewPager;
    private LiveBean data;
    private TextView[] btnTvs = new TextView[3];
    //选项卡被选中和未选中时的字体颜色
    private int onTextColor,offTextColor;
    //viewpage的线条指示器
    private RelativeLayout indicatorView;
    //记录移动的开始位置 初始0
    private int previousPosition = 0;
    //屏幕的宽度
    private int screenWidth;
    private String liveId,count;
    private UserBean userBean;
    private TextView tvTitle,tvContent,tvPeopleNumber,tv_des;
    LandLayoutVideo detailPlayer;
    private OrientationUtils orientationUtils;
    private boolean isPlay;
    private boolean isPause;
    String timeStateName;
    String startTime;
    GSYVideoOptionBuilder builder;


    @Override
    public int getLayout() {
        return R.layout.activity_live_details;
    }

    @Override
    public void findId() {
        tvTitle = findViewById(R.id.tvTitle);
        tv_des = findViewById(R.id.tv_des);
        detailPlayer = findViewById(R.id.detail_player);
        tvPeopleNumber = findViewById(R.id.tvPeopleNumber);
        titleBar = findViewById(R.id.titleBar);
        head_img_right2 = findViewById(R.id.head_img_right2);
        userBean = AppCurrentUser.getInstance().getUserInfo();
    }

    @Override
    public void setListener() {

    }

    @Override
    public void logic() {
        if(getIntent().getExtras()!=null){
            liveId = getIntent().getStringExtra("id");
            count = getIntent().getStringExtra("count");
            String name = getIntent().getStringExtra("name");
            initTitleBar(" ",name,"",this);
            tvPeopleNumber.setText(count+"人在学");
        }
        RichText.initCacheDir(LiveDetails.this);

        head_img_right2.setImageResource(R.mipmap.icon_collect1);
        screenWidth = MainActivity.screenWidth;
        titleBar.setBackgroundColor(ContextCompat.getColor(this, R.color.transparent));

        if(liveId!=null) {
            L.d(liveId);
            mPresenter.getLiveDetails(liveId,null);
        }
    }


    //填充数据
    private void setViewData(boolean isLive) {
        if(data==null)
            return;
        tvTitle.setText(data.getName()+(isLive?"":"(回放)"));
        RichText.from(data.getContent()+"")
                .autoPlay(true) // gif图片是否自动播放
                .scaleType(ImageHolder.ScaleType.center) // 图片缩放方式
                .size(ImageHolder.MATCH_PARENT, ImageHolder.WRAP_CONTENT) // 图片占位区域的宽高
                .into(tv_des); // 设置目标TextView

    }



    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnTv1:
                viewPager.setCurrentItem(0);
                break;
            case R.id.btnTv2:
                viewPager.setCurrentItem(1);
                break;
            case R.id.btnTv3:
                viewPager.setCurrentItem(2);
                break;
        }
        super.onClick(view);
    }

    @Override
    public LivePersenter createPresenter() {
        return new LivePersenter();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

//    //改变收藏状态
//    private void changeCollectionState(String stRecordId){
//        this.stCollectionRecordId = stRecordId;
//        if(stCollectionRecordId==null){
//            head_img_right2.setImageResource(R.mipmap.icon_collect1);
//        }else {
//            head_img_right2.setImageResource(R.mipmap.icon_collect2);
//        }
//    }

    @Override
    public void onPageSelected(int position) {
        //线条指示器移动
        TranslateAnimation ani = new TranslateAnimation(
                previousPosition * screenWidth/3,
                position * screenWidth/3, 0, 0);
        ani.setDuration(200);
        ani.setFillAfter(true);
        ani.setInterpolator(new AccelerateDecelerateInterpolator());
        //播放动画
        indicatorView.startAnimation(ani);
        //将这一次的位置保存起来，作为下一次移动的起始位置
        previousPosition = position;
        for(int i = 0;i<btnTvs.length;i++){
            if(i==position){
                btnTvs[i].setTextColor(onTextColor);
            }
            else {
                btnTvs[i].setTextColor(offTextColor);
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void setLiveList(boolean isSuccess, int page, List<LiveBean> data, String stDescribe) {

    }

    @Override
    public void setLiveDetails(boolean isSuccess, LiveBean data, String stDescribe) {
        if(isSuccess){
            this.data = data;
            Log.e("tag","11111111111");

            timeStateName = data.getTimeStateName();
            startTime = data.getStartTime();


            if(timeStateName!=null && timeStateName.contains("结束")){
                setViewData(false);
                mPresenter.getReplayLiveUrl(AppCurrentUser.getInstance().getToken(),data.getId());
            }else{
                setViewData(true);
                mPresenter.getLiveUrl(AppCurrentUser.getInstance().getToken(),data.getAppName(),data.getId());
            }
        }
    }

    @Override
    public void setLiveUrl(boolean isSuccess, List<String> url) {
        if(isSuccess && null!=url){
           dealVideo(url,true);
        }

        if(startTime!=null){
            if(DateUtil.compareTime(startTime)){//已经开始了

            }else{
                detailPlayer.getStartButton().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ToastUtil.showShortToast(LiveDetails.this,"对不起,直播尚未开始");
                    }
                });
            }
        }
    }


    private int cruPlayPosition=0;
    private void dealVideo(List<String> url,boolean isLive){
        if(isLive){

            List<VideoOptionModel> list = new ArrayList<>();
            //硬解码：1、打开，0、关闭
            VideoOptionModel videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "rtsp_transport", "tcp");
            list.add(videoOptionModel);
            //软解码：1、打开，0、关闭
            videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "rtsp_flags", "prefer_tcp");
            list.add(videoOptionModel);
            videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "allowed_media_types", "video"); //根据媒体类型来配置
            list.add(videoOptionModel);
            videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", 20000);
            list.add(videoOptionModel);
            videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "buffer_size", 1316);
            list.add(videoOptionModel);
            videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "infbuf", 1);  // 无限读
            list.add(videoOptionModel);
            videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzemaxduration", 100);
            list.add(videoOptionModel);
            videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", 10240);
            list.add(videoOptionModel);
            videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "flush_packets", 1);
            list.add(videoOptionModel);
            //  关闭播放器缓冲，这个必须关闭，否则会出现播放一段时间后，一直卡主，控制台打印 FFP_MSG_BUFFERING_START
            videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", 0);
            list.add(videoOptionModel);
            videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_clear", 1);
            list.add(videoOptionModel);
            GSYVideoManager.instance().setOptionModelList(list);
        }

        //增加封面
        ImageView imageView = new ImageView(getApplicationContext());
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        Glide.with(LiveDetails.this).load(data.getCover()).into(imageView);
        detailPlayer.setThumbImageView(imageView);
        resolveNormalVideoUI();

        //外部辅助的旋转，帮助全屏
        orientationUtils = new OrientationUtils(this, detailPlayer);
        //初始化不打开外部的旋转
        orientationUtils.setEnable(false);
        GSYVideoOptionBuilder gsyVideoOption = new GSYVideoOptionBuilder();

        String videoUrl;

        if(isLive && url.size()>2){
            videoUrl=url.get(2);
        }else{
            videoUrl=url.get(0);
            cruPlayPosition=0;
        }

        builder = gsyVideoOption.setThumbImageView(imageView)
                .setIsTouchWiget(true)
                .setRotateViewAuto(false)
                .setLockLand(false)
                .setAutoFullWithSize(true)
                .setShowFullAnimation(false)
                .setNeedLockFull(true)
                .setUrl(videoUrl)
                .setCacheWithPlay(false)
                .setVideoTitle("测试视频")
                .setVideoAllCallBack(new GSYSampleCallBack() {
                    @Override
                    public void onPrepared(String url, Object... objects) {
                        super.onPrepared(url, objects);
                        //开始播放了才能旋转和全屏
                        orientationUtils.setEnable(true);
                        isPlay = true;

                        saveWatching("1");
                    }

                    @Override
                    public void onEnterFullscreen(String url, Object... objects) {
                        super.onEnterFullscreen(url, objects);
                    }

                    @Override
                    public void onAutoComplete(String u, Object... objects) {
                        super.onAutoComplete(u, objects);
                        if(!isLive && builder!=null && cruPlayPosition<url.size()-1){
                            cruPlayPosition++;
                            builder.setUrl(url.get(cruPlayPosition));
                            detailPlayer.getCurrentPlayer().startPlayLogic();
                        }

                    }

                    @Override
                    public void onClickStartError(String url, Object... objects) {
                        super.onClickStartError(url, objects);
                    }

                    @Override
                    public void onQuitFullscreen(String url, Object... objects) {
                        super.onQuitFullscreen(url, objects);
                        if (orientationUtils != null) {
                            orientationUtils.backToProtVideo();
                        }
                    }
                })
                .setLockClickListener((view, lock) -> {
                    if (orientationUtils != null) {
                        //配合下方的onConfigurationChanged
                        orientationUtils.setEnable(!lock);
                    }
                })
                .setGSYVideoProgressListener(new GSYVideoProgressListener() {
                    @Override
                    public void onProgress(int progress, int secProgress, int currentPosition, int duration) {
                        Debuger.printfLog(" progress " + progress + " secProgress " + secProgress + " currentPosition " + currentPosition + " duration " + duration);
                    }
                });
        builder.build(detailPlayer);

        detailPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //直接横屏
                orientationUtils.resolveByClick();

                //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
                detailPlayer.startWindowFullscreen(LiveDetails.this, true, true);
            }
        });
    }

    @Override
    public void setRePlayLiveUrl(boolean isSuccess, List<String> url) {
        if(isSuccess && null!=url){
            dealVideo(url,false);
        }
    }

    private void resolveNormalVideoUI() {
        //增加title
        detailPlayer.getTitleTextView().setVisibility(View.GONE);
        detailPlayer.getBackButton().setVisibility(View.GONE);
    }

    @Override
    public void onBackPressed() {

        if (orientationUtils != null) {
            orientationUtils.backToProtVideo();
        }

        if (GSYVideoManager.backFromWindowFull(this)) {
            return;
        }
        super.onBackPressed();
    }


    @Override
    protected void onPause() {
        getCurPlay().onVideoPause();
        super.onPause();
        isPause = true;
    }

    @Override
    protected void onResume() {
        getCurPlay().onVideoResume(false);
        super.onResume();
        isPause = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isPlay) {
            getCurPlay().release();
            saveWatching("2");
        }
        //GSYPreViewManager.instance().releaseMediaPlayer();
        GSYVideoManager.releaseAllVideos();
        if (orientationUtils != null)
            orientationUtils.releaseListener();
    }



    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //如果旋转了就全屏
        if (isPlay && !isPause) {
            detailPlayer.onConfigurationChanged(this, newConfig, orientationUtils, true, true);
        }
    }

    private GSYVideoPlayer getCurPlay() {
        if (detailPlayer.getFullWindowPlayer() != null) {
            return  detailPlayer.getFullWindowPlayer();
        }
        return detailPlayer;
    }

    private void saveWatching(String state){
        Map map=new HashMap();
        map.put("livePlayId",data.getId());
        map.put("state",state);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),JSON.toJSONString(map));
        RetroFactory.getInstance().saveLiveState(AppCurrentUser.getInstance().getToken(),requestBody)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(String s) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

}
